<?php

namespace app\common\service;

use think\Db;

use think\facade\Cache;

use Firebase\JWT\JWT;

use think\facade\Config;

class OperationToken
{
    /*
     * 生成 token
     */
    public static function createToken($uid, $type)
    {
        $time = time();
        $info_token = [
            'iat' => $time,    // 签发时间
            'exp' => 3600000 + $time,    // 有效时间
            'sign' => base64_encode($uid),    // 签名
            'data' => [
                'uid' => $uid,    // id
                'type' => $type    // 用户还是管理员
            ]
        ];

        $token = JWT::encode($info_token, getJwtKey());

        // 若已登录过，则更新 token
        $exitToken = Db::table('tokens')->where(['uid' => $uid, 'type' => $type])->find();
        if ($exitToken != null) {
            Db::table('tokens')->update(['id' => $exitToken['id'], 'token' => $token, 'exp_time' => $time + 3600000]);
        } else {
            // 若未登录，则插入新记录
            Db::table('tokens')->insert(
                [
                    'uid' => $uid,
                    'token' => $token,
                    'exp_time' => 3600000 + $time,
                    'type' => $type
                ]
            );
        }

        return $token;
    }

}
